using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;

namespace SPTraceView.Model
{
    internal class HistoryList
    {
        private string m_SerializationName;
        private int m_MaxHistoryItems;
        private List<string> m_List = new List<string>();

        public HistoryList(int maxHistoryItems, string serializationName)
        { 
            m_SerializationName = serializationName;
            m_MaxHistoryItems = maxHistoryItems;
        }

        public void Add(string newValue)
        {
            if (newValue == null)
                return;

            newValue = newValue.Trim();
            if (newValue == string.Empty ||
                newValue == "*")
            {
                return;
            }

            int existingIndex = -1;
            for (int i = 0; i < m_List.Count; i++)
			{
                if (m_List[i].Equals(newValue, StringComparison.InvariantCultureIgnoreCase))
                {
                    //Found existing item
                    existingIndex = i;
                    break;
                }
			}

            if (existingIndex != -1)
                m_List.RemoveAt(existingIndex);

            m_List.Insert(0, newValue);

            while (m_List.Count > m_MaxHistoryItems)
                m_List.RemoveAt(m_List.Count - 1);
        }

        public IEnumerable<string> Items
        {
            get { return m_List; }
        }

        public void Deserialize(SerializationInfo info, StreamingContext context)
        {
            int cnt = info.GetInt32(string.Format("{0}_Count", m_SerializationName));
            m_List.Clear();
            for (int i = 0; i < cnt; i++)
            {
                string item = info.GetString(string.Format("{0}_Item_{1}", m_SerializationName, i));
                m_List.Add(item);
            }
        }

        public void Serialize(SerializationInfo info, StreamingContext context)
        {
            info.AddValue(string.Format("{0}_Count", m_SerializationName), m_List.Count);
            for (int i = 0; i < m_List.Count; i++)
            {
                info.AddValue(string.Format("{0}_Item_{1}", m_SerializationName, i), m_List[i]);
            }
        }

        public void CopyFrom(HistoryList copyFrom)
        {
            m_List.Clear();
            m_List.AddRange(copyFrom.m_List);
        }
    }
}
